import {lark} from '@/config';
import {TedisPool} from 'tedis';

const redisPool: TedisPool = ((): TedisPool => {
    if (lark.env.redis.password.length !== 0) {
        return new TedisPool({
            port: lark.env.redis.port,
            host: lark.env.redis.host,
            password: lark.env.redis.password,
        });
    }
    return new TedisPool({
        port: lark.env.redis.port,
        host: lark.env.redis.host,
    });
})();

/**
 * 封装的简易 promise 风格的 redis api
 */
export default class RedisOpts {
    static async set(key: string, value: string): Promise<void> {
        const tedis = await redisPool.getTedis();
        await tedis.set(key, value);
        redisPool.putTedis(tedis);
    }

    static async setex(key: string, second: number, value: string): Promise<void> {
        const tedis = await redisPool.getTedis();
        await tedis.setex(key, second, value);
        redisPool.putTedis(tedis);
    }

    static get(key): Promise<string | number | null> {
        return new Promise<string | number | null>(async (resolve, reject) => {
            const tedis = await redisPool.getTedis();
            const res = await tedis.get(key);
            resolve(res);
            redisPool.putTedis(tedis);
        });
    }
}
